﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Stee.CAP8.MessageBus.Sagas.Core.Sagas
{
    public class InMemorySagaStorage : ISagaStorage
    {
        private static ConcurrentDictionary<Guid, ISagaData> _storageList = new ConcurrentDictionary<Guid, ISagaData>();

        public Task Delete(ISagaData sagaData)
        {
            if (sagaData is null)
            {
                throw new ArgumentNullException(nameof(sagaData));
            }
            var id = sagaData.Id;

            return Task.FromResult(_storageList.TryRemove(id, out ISagaData _));

        }

        public Task<ISagaData> Find(Guid id)
        {
            _storageList.TryGetValue(id, out var sagaData);
            return Task.FromResult(sagaData);
        }

        public Task Insert(ISagaData sagaData)
        {
            if (sagaData is null)
            {
                throw new ArgumentNullException(nameof(sagaData));
            }

            var id = sagaData.Id;
            return Task.FromResult(_storageList.TryAdd(id, sagaData));
        }

        public Task Update(ISagaData sagaData)
        {
            if (sagaData is null)
            {
                throw new ArgumentNullException(nameof(sagaData));
            }

            var id = sagaData.Id;
            return Task.FromResult(
            _storageList.AddOrUpdate(id, sagaData, (k, v) =>
            {
                return v;
            }));
        }
    }
}
